package com.lk.recvice.server.netty;

import com.lk.recvice.server.MyDecoder;
import com.lk.recvice.server.MyServerSocket;
import com.lk.recvice.server.MySocketChannel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class MyServerInitializer extends ChannelInitializer<SocketChannel>{


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        System.out.println(ch.remoteAddress().getHostString()+":"+ch.remoteAddress().getPort());

        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(5, 0, 0, TimeUnit.MINUTES));
//        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
//        pipeline.addLast(new LengthFieldPrepender(4));
        //字符串解码
//        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        //字符串编码
//        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast("decoder", new MyDecoder());
//        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4, -8, 0));
        pipeline.addLast("framedecoder",new LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4));
        //自己定义的处理器
        pipeline.addLast(new MyServerHandler(ch));

        MySocketChannel mySocketChannel = new MySocketChannel();
        mySocketChannel.setSocketChannel(ch);
        MyServerSocket.socketChannel_keepalive.put(ch.id().toString(), mySocketChannel);
        MyServerSocket.socketChannelList_keepalive.add(mySocketChannel);
    }


}
